/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.goods.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.auth.core.util.StpClientUtil;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.biz.modular.goods.entity.BizGoodsLedger;
import vip.xiaonuo.biz.modular.goods.mapper.BizGoodsLedgerMapper;
import vip.xiaonuo.biz.modular.goods.param.ClientGoodsLedgerPageParam;
import vip.xiaonuo.biz.modular.goods.param.ClientUserBorrowPageParam;
import vip.xiaonuo.biz.modular.goods.param.GoodsLedgerQryDto;
import vip.xiaonuo.biz.modular.goods.result.ClientUserBorrowPageResult;
import vip.xiaonuo.biz.modular.goods.result.GoodsLedgerExportResult;
import vip.xiaonuo.biz.modular.goods.result.GoodsLedgerPageResult;
import vip.xiaonuo.biz.modular.goods.service.BizGoodsLedgerService;
import vip.xiaonuo.common.config.ConfigProperties;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.common.util.CommonDownloadUtil;
import vip.xiaonuo.dev.api.DevConfigApi;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 物品台账Service接口实现类
 *
 * @author 古月墨塵
 * @date 2022/11/26 11:24
 **/
@Service
@Transactional
public class BizGoodsLedgerServiceImpl extends ServiceImpl<BizGoodsLedgerMapper, BizGoodsLedger> implements BizGoodsLedgerService {
    @Resource
    private DevConfigApi devConfigApi;

    @Override
    public Page<GoodsLedgerPageResult> page(GoodsLedgerQryDto dto) {
        //当前用户
        if (!StpUtil.hasRoleOr("superAdmin", "sysAdmin")) {
            SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
            dto.setUserId(saBaseLoginUser.getId());
        }
        return this.baseMapper.getPageList(CommonPageRequest.defaultPageForDto(dto), dto);
    }

    @Override
    public Page<ClientUserBorrowPageResult> pageClientUserBorrowRecords(ClientUserBorrowPageParam param) {
        String userId = StpClientUtil.getLoginIdAsString();
        param.setUserId(userId);
        Page<ClientUserBorrowPageResult> page = getBaseMapper().pageUserBorrowRecords(CommonPageRequest.defaultPageForDto(param), param);
        String baseUrl = devConfigApi.getValueByKey("BACKEND_BASE_URL");
        if (ObjectUtil.isEmpty(baseUrl)) {
            throw new CommonException("服务端URL未正确配置");
        }
        page.getRecords().forEach(item -> item.setGoodsImg(getImageUrl(item.getGoodsImg(), baseUrl)));
        return page;
    }

    private String getImageUrl(String fileId, String baseUrl) {
        if (StringUtils.isEmpty(fileId)) return "";
        return baseUrl + "/dev/file/download?id=" + fileId;
    }

    @Override
    public Page<GoodsLedgerPageResult> pageClientGoodsLedgerRecords(ClientGoodsLedgerPageParam param) {
        GoodsLedgerQryDto dto = new GoodsLedgerQryDto();
        dto.setGoodsId(param.getGoodsId());
        return this.baseMapper.getPageList(CommonPageRequest.defaultPageForDto(dto), dto);
    }

    @Override
    public void export(GoodsLedgerQryDto dto, HttpServletResponse response) {
        File tempFile = null;
        try {
            //当前用户
            if (!StpUtil.hasRoleOr("superAdmin", "sysAdmin")) {
                SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
                dto.setUserId(saBaseLoginUser.getId());
            }

            List<GoodsLedgerExportResult> exportList = new ArrayList<>();

            List<GoodsLedgerPageResult> list = this.baseMapper.getResultList(dto);
            for (GoodsLedgerPageResult item : list) {
                GoodsLedgerExportResult goodsLedgerExportResult = new GoodsLedgerExportResult();
                BeanUtil.copyProperties(item, goodsLedgerExportResult);
                goodsLedgerExportResult.setLedgerTypeStr(this.getTypeStr(item.getLedgerType()));
                String record = "合格:{0}\r\n不合格:{1}\r\n未检查:{2}\r\n";
                goodsLedgerExportResult.setCollectionInspectionRecord(MessageFormat.format(record, item.getBorCheckQualifyNum(), item.getBorCheckUnqNum(), item.getBorCheckNotNum()));
                goodsLedgerExportResult.setReturnInspectionRecord(MessageFormat.format(record, item.getRetCheckQualifyNum(), item.getRetCheckUnqNum(), item.getRetCheckNotNum()));
                exportList.add(goodsLedgerExportResult);
                if (StringUtils.isNotBlank(item.getCreateUserName())) {
                    goodsLedgerExportResult.setCreateUserName(item.getCreateUserName() + "(" + item.getCreateUserAccount() + ")");
                }
                if (StringUtils.isNotBlank(item.getDeliveryUserName())) {
                    goodsLedgerExportResult.setDeliveryUserName(item.getDeliveryUserName() + "(" + item.getDeliveryUserAccount() + ")");
                }
                if (StringUtils.isNotBlank(item.getWarehouseUserName())) {
                    goodsLedgerExportResult.setWarehouseUserName(item.getWarehouseUserName() + "(" + item.getWarehouseUserAccount() + ")");
                }
            }
            String fileName = "物品台账清单";
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(fileName, "物品台账列表"),
                    GoodsLedgerExportResult.class, exportList);
            tempFile = FileUtil.file(FileUtil.getTmpDir() + FileUtil.FILE_SEPARATOR + fileName + ".xls");
            BufferedOutputStream outputStream = FileUtil.getOutputStream(tempFile);
            workbook.write(outputStream);
            outputStream.close();
            CommonDownloadUtil.download(tempFile, response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonException("物品台账导出失败");
        } finally {
            FileUtil.del(tempFile);
        }
    }

    @Override
    public void exportForReagent(GoodsLedgerQryDto dto, HttpServletResponse response) {
        File tempFile = null;
        try {
            //当前用户
            if (!StpUtil.hasRoleOr("superAdmin", "sysAdmin")) {
                SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
                dto.setUserId(saBaseLoginUser.getId());
            }

            List<GoodsLedgerExportResult> exportList = new ArrayList<>();

            List<GoodsLedgerPageResult> list = this.baseMapper.getResultList(dto);
            for (GoodsLedgerPageResult item : list) {
                GoodsLedgerExportResult goodsLedgerExportResult = new GoodsLedgerExportResult();
                BeanUtil.copyProperties(item, goodsLedgerExportResult);
                goodsLedgerExportResult.setLedgerTypeStr(this.getTypeStr(item.getLedgerType()));
                String record = "合格:{0}\r\n不合格:{1}\r\n未检查:{2}\r\n";
                goodsLedgerExportResult.setCollectionInspectionRecord(MessageFormat.format(record, item.getBorCheckQualifyNum(), item.getBorCheckUnqNum(), item.getBorCheckNotNum()));
                goodsLedgerExportResult.setReturnInspectionRecord(MessageFormat.format(record, item.getRetCheckQualifyNum(), item.getRetCheckUnqNum(), item.getRetCheckNotNum()));
                exportList.add(goodsLedgerExportResult);
                if (StringUtils.isNotBlank(item.getCreateUserName())) {
                    goodsLedgerExportResult.setCreateUserName(item.getCreateUserName() + "(" + item.getCreateUserAccount() + ")");
                }
                if (StringUtils.isNotBlank(item.getDeliveryUserName())) {
                    goodsLedgerExportResult.setDeliveryUserName(item.getDeliveryUserName() + "(" + item.getDeliveryUserAccount() + ")");
                }
                if (StringUtils.isNotBlank(item.getWarehouseUserName())) {
                    goodsLedgerExportResult.setWarehouseUserName(item.getWarehouseUserName() + "(" + item.getWarehouseUserAccount() + ")");
                }
            }
            String fileName = "试剂台账清单";
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(fileName, "试剂台账列表"),
                    GoodsLedgerExportResult.class, exportList);
            tempFile = FileUtil.file(FileUtil.getTmpDir() + FileUtil.FILE_SEPARATOR + fileName + ".xls");
            BufferedOutputStream outputStream = FileUtil.getOutputStream(tempFile);
            workbook.write(outputStream);
            outputStream.close();
            CommonDownloadUtil.download(tempFile, response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonException("试剂台账导出失败");
        } finally {
            FileUtil.del(tempFile);
        }
    }

    private String getTypeStr(Integer ledgerType) {
        switch (ledgerType) {
            case 0:
                return "首次入库";
            case 1:
                return "启用";
            case 2:
                return "维修";
            case 3:
                return "报废";
            case 10:
                return "取用";
            default:
                return "未知";
        }
    }
}
